package com.yanqu.road.dao.impl.giftKey;

import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.db.DbParameter;
import com.yanqu.road.dao.impl.TempDataObjectDao;
import com.yanqu.road.entity.giftKey.GiftKeyInfo;
import com.yanqu.road.entity.giftKey.GiftKeyUse;
import com.yanqu.road.utils.string.StringUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GiftKeyDaoImpl extends TempDataObjectDao<GiftKeyUse> {

    public boolean addGiftUseList(List<GiftKeyUse> list) {
        if(list.size() <= 0){
            return true;
        }
        boolean result = false;
        getDb().setConnName(DbNameStrategy.getUserDb());
        String sql = "INSERT INTO t_u_exchange_code_use(configId,userId,exchangeCode,useTime"
                + ") VALUES(?,?,?,?)";
        List<Map<Integer, DbParameter>> mapList = new ArrayList<>();
        for (GiftKeyUse data : list) {
            Map<Integer, DbParameter> para = new HashMap<>();
            int i = 1;
            para.put(i++, new DbParameter(Types.INTEGER, data.getConfigId()));
            para.put(i++, new DbParameter(Types.BIGINT, data.getUserId()));
            para.put(i++, new DbParameter(Types.VARCHAR, data.getExchangeCode()));
            para.put(i++, new DbParameter(Types.BIGINT, data.getUseTime()));
            mapList.add(para);
        }
        if (getDb().executeBatchQuery(sql, mapList) > -1) {
            result = true;
        }
        return result;
    }

    public List<GiftKeyUse> getUserGiftKeyUseList(long userId) {
        List<GiftKeyUse> dataMap = new ArrayList<>();
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select * from t_u_exchange_code_use where userid = ?";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(sql);
            int i = 1;
            call.setLong(i++,userId);
            rs = call.executeQuery();
            while (rs.next()) {
                GiftKeyUse data = initGiftKeyUse(rs);
                dataMap.add(data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;
    }

    public List<GiftKeyUse> getGiftKeyUseList(long userId) {
        List<GiftKeyUse> dataMap = new ArrayList<>();
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select * from t_s_exchange_code_use where userid = ?";
        try {
            getDb().setConnName(DbNameStrategy.getServerDb());
            call = getDb().getConnection().prepareCall(sql);
            int i = 1;
            call.setLong(i++,userId);
            rs = call.executeQuery();
            while (rs.next()) {
                GiftKeyUse data = initGiftKeyUse(rs);
                dataMap.add(data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;
    }


    private GiftKeyUse initGiftKeyUse(ResultSet rs) throws SQLException {
        GiftKeyUse data = new GiftKeyUse();
        data.setUserId(rs.getLong("userId"));
        data.setConfigId(rs.getInt("configId"));
        data.setExchangeCode(rs.getString("exchangeCode"));
        data.setUseTime(rs.getLong("useTime"));
        return data;
    }

    public GiftKeyInfo getGiftKeyInfo(String key) {
        GiftKeyInfo giftKeyInfo = null;
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "SELECT * FROM t_s_exchange_code_list ecl " +
                "LEFT JOIN t_s_exchange_code_conf ecc on ecl.configId = ecc.id " +
                "WHERE exchangeCode = ?";
        try {
            getDb().setConnName(DbNameStrategy.getServerDb());
            call = getDb().getConnection().prepareCall(sql);
            call.setString(1, key);
            rs = call.executeQuery();
            while (rs.next()) {
                giftKeyInfo = new GiftKeyInfo();
                giftKeyInfo.setExchangeCode(rs.getString("exchangeCode"));
                giftKeyInfo.setConfigId(rs.getInt("configId"));
                giftKeyInfo.setCodeType(rs.getInt("codeType"));
                giftKeyInfo.setChannelIdList(StringUtils.stringToIntegerList(rs.getString("channelId"),","));
                giftKeyInfo.setServerIdList(StringUtils.stringToLongList(rs.getString("serverId"),","));
                giftKeyInfo.setStartTime(rs.getDate("startTime").getTime()/1000);
                giftKeyInfo.setEndTime(rs.getDate("endTime").getTime()/1000);
                giftKeyInfo.setReward(rs.getString("awards"));
                giftKeyInfo.setMaxLimit(rs.getInt("maxLimit"));
                giftKeyInfo.setUseTimes(rs.getInt("state"));
                giftKeyInfo.setReceiveNum(rs.getInt("receiveNum"));
                giftKeyInfo.setEnable(rs.getBoolean("isEnable"));
                giftKeyInfo.setAppId(rs.getString("appId"));
                giftKeyInfo.setPlayType(rs.getInt("playType"));
                giftKeyInfo.setSlideSettings(rs.getString("slideSettings"));
            }
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return giftKeyInfo;
    }


    @Override
    protected boolean addData(GiftKeyUse data) {
        PreparedStatement call = null;
        String sql = "INSERT INTO t_s_exchange_code_use(configId,userId,exchangeCode,useTime"
                + ") VALUES(?,?,?,?)";
        try {
            getDb().setConnName(DbNameStrategy.getServerDb());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setInt(i++, data.getConfigId());
            call.setLong(i++, data.getUserId());
            call.setString(i++, data.getExchangeCode());
            call.setLong(i++, data.getUseTime());
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    @Override
    protected boolean updateData(GiftKeyUse data) {
        return false;
    }

    @Override
    protected GiftKeyUse parseData(ResultSet rs) throws SQLException {
        GiftKeyUse data = new GiftKeyUse();
        data.setConfigId(rs.getInt("configId"));
        data.setUserId(rs.getLong("userId"));
        data.setExchangeCode(rs.getString("exchangeCode"));
        data.setUseTime(rs.getLong("useTime"));
        return data;
    }

    public int updateNormalGiftKeyUseTimes(String exchangeKey) {
        String sql = "update t_s_exchange_code_list set state=state+1 where exchangeCode=?";
        getDb().setConnName(DbNameStrategy.getServerDb());
        Map<Integer, DbParameter> para = new HashMap<>();
        para.put(1, new DbParameter(Types.NVARCHAR, exchangeKey));
        return getDb().executeNoneQuery(sql, para);
    }

    public int updateOnceGiftKeyUseTimes(String exchangeKey) {
        String sql = "update t_s_exchange_code_list set state=1 where exchangeCode=?";
        getDb().setConnName(DbNameStrategy.getServerDb());
        Map<Integer, DbParameter> para = new HashMap<>();
        para.put(1, new DbParameter(Types.NVARCHAR, exchangeKey));
        return getDb().executeNoneQuery(sql, para);
    }
}
